package com.lcw.lostandfound.controller;

import com.alibaba.fastjson.JSON;
import com.lcw.lostandfound.mapper.AdminMapper;
import com.lcw.lostandfound.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class AdminController {
    @Autowired
    private AdminMapper adminMapper;
    @RequestMapping("/admin/login")
    public String login(){
        return "admin/login";
    }
    @RequestMapping("/admin/doLogin")
    public String doLogin(HttpSession session, Model model,String name, String password){
        Admin admin = adminMapper.findAdmin(name, password);
        if (admin!=null){
            session.setAttribute("admin",admin);
            model.addAttribute("admins",adminMapper.findAllAdmin());
            return "admin/index";
        }
        return "admin/login";
    }
    @RequestMapping("/admin/logout")
    public String logout(HttpSession session){
        session.removeAttribute("admin");
        return "admin/login";
    }
    @ResponseBody
    @RequestMapping("/addAdmin")
    public String addAdmin(Admin admin){
        if (adminMapper.addAdmin(admin)>0) {
            return "true";
        }
        return "false";
    }
    @ResponseBody
    @RequestMapping("/deleteAdmin")
    public String deleteAdmin(Integer id){
        if (adminMapper.deleteAdminById(id)>0) {
            return "true";
        }
        return "false";
    }
    @ResponseBody
    @RequestMapping("/queryAdmin")
    public String queryAdmin(Integer id){
        Admin admin = adminMapper.findAdminById(id);
        System.out.println(JSON.toJSONString(admin));
        return JSON.toJSONString(admin);
    }
    @RequestMapping("/admin/index")
    public String index(Model model){
        model.addAttribute("admins",adminMapper.findAllAdmin());
        return "admin/index";
    }
    @ResponseBody
    @RequestMapping("/updateAdmin")
    public String updateAdmin(Admin admin){
        if (adminMapper.updateAdmin(admin)>0){
            return "true";
        }
        return "false";
    }
}
